﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JeanFish.Blog.Business
{
    public sealed class Blog : BlogBase
    {
        internal async Task LoadAsync()
        {
            this.Onwer = await BlogService.Current.LoadBlogOnwerAsync(this);
            await BlogService.Current.ListPostsAsync(this, new Paging(0));
        }
        public Guid ID
        {
            get { return Guid.Parse(this._id); }
            set
            {

                this.SetProperty<string>("ID", value.ToString("N"), ref this._id);
            }
        }
        public string Name
        {
            get { return this._name; }
            set
            {
                this.SetProperty<string>("Name", value, ref this._name);
            }
        }
        public User Onwer
        {
            get;
            private set;
        }
        //public List<Post> Posts
        //{
        //    get;
        //    private set;
        //}
        public static implicit operator Blog(Storage.Blog blog)
        {
            var b = new Blog();
            b.Copy(blog);
            return b;
        }
        public sealed override void AcceptChanges()
        {
            base.AcceptChanges();
        }
        protected async override Task<SavedResult> SaveAsync()
        {
            return await BlogService.Current.SaveBlogAsync(this);
        }
        internal void Post_Saved(object sender, SavedEventArgs e)
        {
            if (e.Result == SavedResult.OK)
            {
                var postId = Guid.Parse(e.ID);
                var post = sender as Post;
                if (post != null && !post.IsChanged)
                {
                    if (post.Labels.HasFlag(PostLabel.Deleted))
                    {
                        this.Saved -= post.Blog_Saved;
                    }
                }
            }
        }
        public async Task<Post> GetPostAsync(Guid postId)
        {
            return await BlogService.Current.GetPostAsync(this, postId);

        }
        public async Task<IEnumerable<Post>> ListPosts(Paging paging)
        {
            return await BlogService.Current.ListPostsAsync(this, paging);
        }
    }
}
